<template>
  <el-cascader
    v-if="show"
    ref="elcascader"
    v-model="carModel"
    :props="props"
    clearable
    filterable
    :emitPath="!emitPath"
    @change="change"
    :disabled="disabled"
    placeholder="请选择品牌/车系/车型"
  ></el-cascader>
</template>

<script>
import {
  getAllBrand,
  getSeries,
  getModelTimeType,
  getModelRank
} from '@/api/after-sale/systemManage/carModel'
// 处理数据
function formData(data, leaf = false) {
  let nodes = []
  if (Array.isArray(data) && data.length > 0) {
    nodes = data.map((e) => {
      const t =
        e instanceof Object && 'id' in e && ('name' in e || 'modelName' in e)
      return (e = {
        value: t ? e.id : e,
        label: t ? (e.name ? e.name : e.modelName) : e,
        leaf
      })
    })
  }
  return nodes
}
export default {
  name: 'CarModel',
  model: {
    props: 'value',
    event: 'input'
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return ['', '', '', '']
      }
    },
    emitPath: {
      // 是否值返回车型
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    //TODO 是否能单选某一节点，属性
    checkStrictly:{
       type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: true,
      carModel: [],
      props: {
        lazy: true,
        value: 'value',
        label: 'label',
        lazyLoad(node, resolve) {
          const { level, root, value, path } = node
          if (level == 0 && root) {
            getAllBrand().then((res) => {
              const { data, success } = res
              resolve(formData(success ? res.data : []))
            })
          } else if (level == 1) {
            getSeries(value).then((res) => {
              const { data, success } = res
              resolve(formData(success ? res.data : []))
            })
          } else if (level == 2) {
            getModelTimeType(path[0], path[1]).then((res) => {
              const { data, success } = res
              resolve(formData(success ? res.data : []))
            })
          } else if (level == 3) {
            getModelRank(path[0], path[1], path[2]).then((res) => {
              const { data, success } = res
              resolve(formData(success ? res.data : [], true))
            })
          }
        }
      }
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(newValue, oldValue) {
        this.carModel = newValue
        this.$emit('input', newValue)
      }
    }
  },
  methods: {
    /**
     * 获取当前节点中文标签
     */
    getLabels() {
      const value = this.$refs.elcascader.getCheckedNodes()[0]
      return value ? value.pathLabels : ['', '', '', '']
    },
    change(value) {
      this.$emit('input', value)
    }
  },
  mounted() {
    this.carModel = this.value
  }
}
</script>
